<template>
  <div>
    <div class="zx-div" v-if="type == 'text'">
      <input type="text" v-model="text" v-maxlength:text="maxlength" />
      <span class="zx-tip"></span>
    </div>
    <div class="zx-div" v-if="type == 'textarea'">
      <textarea
        v-model="textarea"
        v-maxlength:textarea="maxlength"
        cols="30"
        rows="10"
      ></textarea>
      <span class="zx-tip"></span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: "",
      textarea: "",
    };
  },
  props: {
    maxlength: {
      type: Number,
      defaule: 0,
    },
    type: {
      type: String,
      defaule: "text",
    },
  },
  directives: {
    maxlength: {
      inserted(el, binding) {
        el.nextElementSibling.innerHTML = `0/${binding.value}`;
      },
      update(el, binding) {
        el.nextElementSibling.innerHTML = `${el.value.length}/${binding.value}`;
        el.addEventListener("input", (ele) => {
          let val = ele.target.value.slice(0, binding.value);
          el.value = val;
          console.log(vnode.context[binding.arg] )
          vnode.context[binding.arg] = el.value;
          if (el.value.length == binding.value) {
            el.style = "color:red";
          } else {
            el.style = "";
          }
        });
      },
    },
  },
};
</script>

<style>
.zx-div {
    display: inline-block;
    position: relative;
}

span.zx-tip {
    position: absolute;
    right: 3px;
    bottom: 3px;
    font-size: 12px;
}
</style>